<template>
  <!-- 公告管理主组件 -->
  <div class="class-announcements">
    <!-- 搜索过滤卡片 -->
    <el-card class="filter-card">
      <!-- 响应式布局容器，栅格间距20px -->
      <el-row :gutter="20">
        <!-- 班级搜索栏（占8列） -->
        <el-col :span="8">
          <el-form-item label="班级">
            <!-- 班级名称关键词输入框，回车键触发查询 -->
            <el-input v-model="filterForm.className" placeholder="请输入班级名称关键词" @keyup.enter="fetchAnnouncements" />
          </el-form-item>
        </el-col>

        <!-- 公告标题搜索栏（占8列） -->
        <el-col :span="8">
          <el-form-item label="公告标题">
            <!-- 公告标题输入框，回车键触发查询 -->
            <el-input v-model="filterForm.title" placeholder="请输入公告标题" @keyup.enter="fetchAnnouncements" />
          </el-form-item>
        </el-col>

        <!-- 操作按钮栏（占8列） -->
        <el-col :span="8">
          <el-form-item>
            <!-- 查询按钮（触发数据加载） -->
            <el-button type="primary" @click="fetchAnnouncements">查询</el-button>
            <!-- 重置按钮（清空搜索条件） -->
            <el-button type="default" @click="resetFilter">重置</el-button>
            <!-- 发布公告按钮（打开发布弹窗） -->
            <el-button type="success" @click="showPublishDialog">发布公告</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 公告列表卡片 -->
    <el-card class="announcement-list-card">
      <!-- 数据表格组件，展示公告列表 -->
      <el-table :data="announcementList" stripe border>
        <!-- 公告标题列 -->
        <el-table-column prop="title" label="公告标题" min-width="100" />
        <!-- 公告内容列 -->
        <el-table-column prop="content" label="公告内容" min-width="80" />
        <!-- 班级列（展示关联班级名称） -->
        <el-table-column prop="classNames" label="班级" min-width="100" />
        <!-- 发布时间列（展示格式化后的时间） -->
        <el-table-column prop="publishTime" label="发布时间" min-width="100" />
        <!-- 操作列（查看/编辑/删除按钮） -->
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <div class="table-actions">
              <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                     :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" />
    </el-card>

    <!-- 发布/编辑公告弹窗 -->
    <el-dialog v-model="publishDialogVisible" title="发布公告" width="50%">
      <el-form :model="publishForm" ref="publishFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公告标题" prop="title">
              <el-input v-model="publishForm.title" required />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公告内容" prop="content">
              <el-input type="textarea" v-model="publishForm.content" :rows="10" required />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择班级" prop="classNames">
              <el-select v-model="publishForm.classNames" clearable placeholder="请选择" required>
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="publishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPublishForm">发布</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 公告详情弹窗 -->
    <el-dialog v-model="viewDialogVisible" title="公告详情" width="50%">
      <el-card>
        <!-- 详情头部 -->
        <div class="detail-header">
          <h3 class="detail-title">{{ viewAnnouncement.title }}</h3>
          <!-- 标题 -->
          <!-- 元数据信息（班级、发布者、时间、状态） -->
          <div class="detail-meta">
            <span class="detail-meta-item">发布班级：{{ viewAnnouncement.classNames }}</span>
            <span class="detail-meta-item">发布时间：{{ viewAnnouncement.publishTime }}</span>
          </div>
        </div>
        <!-- 富文本内容展示（需注意XSS安全） -->
        <div class="detail-content" v-html="viewAnnouncement.content"></div>
      </el-card>

      <!-- 详情弹窗关闭按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from "vue";
  import axios from "axios";
  import { ElMessage, ElMessageBox } from "element-plus";
  const filterForm = reactive({
    className: "", // 班级名称关键词（用于模糊查询）
    title: "" // 公告标题关键词
  });

  //发布/编辑表单的填写
  const publishForm = reactive({
    notificationId: "",
    title: "",
    classNames: "",
    content: ""
  });

  // 详情展示数据（响应式）
  const viewAnnouncement = reactive({
    title: "",
    classNames: "", // 班级名称（展示用）
    publishTime: "", // 发布时间（格式化后）
    content: ""
  });

  // 列表数据相关
  const announcementList = ref([]); // 公告列表数据
  const classOptions = ref([]); // 班级选项（可能用于下拉选择，当前代码未使用）
  const total = ref(0); // 总数据量
  const pageSize = ref(10); // 每页条数
  const currentPage = ref(1); // 当前页码
  const publishDialogVisible = ref(false); // 发布弹窗显示状态
  const viewDialogVisible = ref(false); // 详情弹窗显示状态
  const publishFormRef = ref(null); // 发布表单引用
  const options = ref([]);//获取教学安排学生班级名称表

  // 生命周期钩子
  onMounted(async () => {
    // 初始化时加载班级列表（可能用于后续优化为下拉选择）
    // 初始化时加载公告列表
    await fetchAnnouncements();
    await fetchClassOptions();
  });

  const fetchAnnouncements = async () => {
    try {
      // 构建请求参数（包含分页和搜索条件）
      const formData = new FormData();
      formData.append("teacherId", localStorage.getItem("teacherId"));
      formData.append("page", currentPage.value);
      formData.append("size", pageSize.value);
      formData.append("className", filterForm.className);
      formData.append("title", filterForm.title);
      // console.log(formData);

      // 调用接口获取数据
      const response = await axios.post(
              "/notifications/getNotificationList",
              formData
      );

      // console.log(response);
      // 解析响应数据，进行数据筛选
      if (response.data.flag == false) {
        ElMessage.error("未查询到信息");
        announcementList.value = [];
        total.value = 0;
      } else {
        const filteredList = response.data.result.map(announcement => {
          return {
            title: announcement.title,
            content: announcement.content,
            classNames: announcement.classNames,
            publishTime: announcement.publishTime,
            notificationId: announcement.notificationId
          };
        });
        announcementList.value = filteredList;
        total.value = response.data.total || 0;
      }
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("完整错误信息", error.response || error);
      }
      console.error("获取公告列表失败", error);
      ElMessage.error("获取公告列表失败，请稍后重试");
    }
  };

  //获取教学安排列表
  const fetchClassOptions = async () => {
    try {
      const response = await axios.get( `/teaches/getClassNamesListByTeacherId?teacherId=${localStorage.getItem('teacherId')}`);
      if (response.data.flag==true) {
        options.value = response.data.result.map((item) => ({
          label: item,
          value: item
        }));
      } else {
        ElMessage.error("未有教学安排");
      }
    } catch (error) {
      console.error("获取班级列表失败", error);
      ElMessage.error("获取班级列表失败，请稍后重试");
    }
  };

  // ------------------------------
  // 操作方法
  // ------------------------------
  // 重置搜索条件
  const resetFilter = () => {
    filterForm.className = "";
    filterForm.title = "";
    // 重置列表和分页状态
    // 恢复默认时的无条件查询
    announcementList.value = [];
    total.value = 0;
    fetchAnnouncements();
  };

  // 打开发布/编辑弹窗
  const showPublishDialog = (announcement = null) => {
    // 初始化表单数据：编辑时填充原有数据，新建时清空
    publishDialogVisible.value = true; // 显示弹窗
    publishForm.notificationId = announcement ? announcement.notificationId : "";
    publishForm.title = announcement ? announcement.title : "";
    publishForm.classNames = announcement ? announcement.classNames : "";
    publishForm.content = announcement ? announcement.content : "";
  };

  // 提交发布/编辑表单
  const submitPublishForm = async () => {
    // 表单必填项校验
    if (!publishForm.title) {
      ElMessage.warning("请输入公告标题");
      return;
    }
    if (!publishForm.classNames) {
      ElMessage.warning("请输入班级");
      console.log(publishForm.classNames);
      return;
    }
    if (!publishForm.content) {
      ElMessage.warning("请输入公告内容");
      return;
    }

    try {
      // 创建FormData对象（用于上传表单数据）
      const formData = new FormData();
      formData.append("title", publishForm.title);
      console.log(publishForm.classNames.label);
      formData.append("classNames", publishForm.classNames.label); // 班级ID字符串（需按接口要求格式，如逗号分隔）
      formData.append("content", publishForm.content);
      if (publishForm.notificationId) {
        formData.append("notificationId", publishForm.notificationId);
      }
      formData.append("teacherId", localStorage.getItem("teacherId"));
      // console.log(formData);
      // 发送请求（根据是否有ID判断是新增还是更新）
      const response = await axios.post(
              publishForm.notificationId
                      ? "/notifications/updateNotification" // 编辑接口
                      : "/notifications/saveNotification", // 新增接口
              formData
      );
      if (response.data.flag === true) {
        ElMessage.success(
                publishForm.notificationId ? "公告更新成功" : "公告发布成功"
        );
        publishDialogVisible.value = false; // 关闭弹窗
        fetchAnnouncements(); // 刷新列表
      } else {
        ElMessage.error(response.data.reason || "操作失败，请稍后重试");
      }
    } catch (error) {
      console.error("发布/更新公告失败", error);
      ElMessage.error("发布/更新公告失败，请稍后重试");
    }
  };

  // 查看公告详情
  const handleView = async announcement => {
    try {
      if (announcement != null) {
        viewDialogVisible.value = true; // 显示详情弹窗
        viewAnnouncement.classNames = announcement.classNames;
        viewAnnouncement.content = announcement.content;
        viewAnnouncement.publishTime = announcement.publishTime;
        viewAnnouncement.title = announcement.title;
      } else {
        ElMessage.error(response.data.message || "获取公告详情失败");
      }
    } catch (error) {
      console.error("获取公告详情失败", error);
      ElMessage.error("获取公告详情失败，请稍后重试");
    }
  };

  // 编辑公告（复用发布弹窗）
  const handleEdit = announcement => {
    console.log(announcement);
    showPublishDialog(announcement); // 传入当前公告数据，填充编辑表单
  };

  // 关闭公告（设置状态为closed）
  const handleClose = async announcement => {
    // 确认对话框
    ElMessageBox.confirm(
            `确定要关闭公告 "${announcement.title}" 吗？关闭后学生将无法查看。`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
    )
  };

  // 删除公告（永久删除）
  // 删除公告（永久删除）
  const handleDelete = async announcement => {
    // 危险操作确认对话框
    ElMessageBox.confirm(
            `确定要删除公告 "${announcement.title}" 吗？删除后将无法恢复。`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "danger"
            }
    )
            .then(async () => {
              try {
                // 调用删除接口
                const response = await axios.delete(
                        `/notifications/removeNotificationById?notificationId=${announcement.notificationId}`
                );

                if (response.data.flag === true) {
                  // 假设后端返回的成功的code是200
                  ElMessage.success("公告已成功删除");
                  fetchAnnouncements(); // 刷新列表
                } else {
                  ElMessage.error(response.data.message || "操作失败，请稍后重试");
                }
              } catch (error) {
                console.error("删除公告失败", error);
                ElMessage.error("删除公告失败，请稍后重试");
              }
            })
            .catch(() => {
              // 取消操作时的处理（空操作）
            });
  };
  // ------------------------------
  // 分页控制方法
  // ------------------------------
  // 每页条数变化时触发
  const handleSizeChange = newSize => {
    currentPage.value = 1; //重置页大小时返回第一页
    pageSize.value = newSize;
    fetchAnnouncements(); // 重新加载数据
  };

  // 当前页码变化时触发
  const handleCurrentChange = newPage => {
    currentPage.value = newPage;
    fetchAnnouncements(); // 重新加载数据
  };
</script>

<style scoped>
  .class-announcements {
    padding: 20px;
    /* 容器内边距 */
  }

  .filter-card {
    margin-bottom: 20px;
    /* 搜索卡片底部间距 */
  }

  .announcement-list-card {
    min-height: 500px;
    /* 列表卡片最小高度，防止内容较少时布局塌陷 */
  }

  .pagination {
    margin-top: 20px;
    /* 分页组件顶部间距 */
    text-align: right;
    /* 分页按钮右对齐 */
  }

  .detail-header {
    margin-bottom: 20px;
    /* 详情头部底部间距 */
  }

  .detail-title {
    font-size: 20px;
    /* 标题字体大小 */
    font-weight: bold;
    /* 标题加粗 */
    margin-bottom: 10px;
    /* 标题底部间距 */
  }

  .detail-meta {
    color: #909399;
    /* 元数据字体颜色（浅灰色） */
    font-size: 14px;
    /* 元数据字体大小 */
  }

  .detail-meta-item {
    margin-right: 20px;
    /* 元数据项间距 */
  }

  /* .detail-content {
    margin-bottom: 20px;
    height: 100px;
    line-height: 1.8;
  } */
  .detail-content {
    margin-bottom: 20px;
    height: 200px;
    /* 调整高度以适应内容 */
    padding: 10px;
    /* 添加内边距 */
    border: 1px solid #dcdfe6;
    /* 添加边框 */
    border-radius: 4px;
    /* 添加圆角 */
    background-color: #f5f7fa;
    /* 添加背景颜色 */
    line-height: 1.8;
    overflow-y: auto;
    /* 如果内容超出高度，则显示滚动条 */
    word-wrap: break-word;
    /* 处理长单词换行 */
  }

  /* 样式穿透 */
  ::v-deep .el-table td.el-table__cell div {
    box-sizing: border-box;
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>